import React, {useCallback, useEffect, useState} from "react"
import {Button, Col, Form, Row, Select, Space, Table} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import FormDrawer from "../../components/FormDrawer";
import DataPageLayout from "../../components/DataPageLayout";
import AuthorizationResource from "../../components/AuthorizationResource";
import {NumberIdAndName} from "../../types/BasicModels";
import {
    createProcurementReturn,
    getAllProcurementReturnCreatedEmployees, ProcurementReturnStatus, procurementReturnStatuses, procurementReturnStatusMap,
    QueryProcurementReturnResponse,
    queryProcurementReturns
} from "../../apis/ProcurementReturnApi";
import {useNavigate, useSearchParams} from "react-router-dom";
import {Pageable} from "../../utils/Page";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {Link} from "react-router-dom";
import {createProcurementSupplier, getAllProcurementSupplier} from "../../apis/ProcurementSupplierApi";
import {useGlobalStyle} from "../../global.style";
import {FormInstance} from "antd/es/form/hooks/useForm";
import {DATE_WITH_TIME_FORMATER, YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";
import QuickCreatableSelectFormItem from "../QuickCreatableSelectFormItem";

export interface pageProps {

}

export interface ProcurementReturnFormData {
    supplierId: number
}


const ProcurementReturnPage: React.FC<pageProps> = (props) => {

    let globalStyle = useGlobalStyle();
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryProcurementReturnResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    let [urlSearchParams] = useSearchParams();
    const [supplierIds, setMarketIds] = useState<number[]>(urlSearchParams.getAll("supplierIds").map(it => parseInt(it)))
    const [createdByIds, setCreatedByIds] = useState<number[]>([])


    const [procurementReturnSuppliers, setProcurementReturnSuppliers] = useState<Array<NumberIdAndName>>([])
    function queryAllProcurementSupplier() {
        return getAllProcurementSupplier().then(response => {
            setProcurementReturnSuppliers(response.data)
        })
    }
    useEffect(() => {
        queryAllProcurementSupplier();
    }, []);

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [status, setStatus] = useState<ProcurementReturnStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryProcurementReturns({
            supplierIds,
            createdByIds,
            startDate: startDate ? startDate.toString() : undefined,
            endDate: endDate ? endDate.toString() : undefined,
            status,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), supplierIds, createdByIds, startDate, endDate, status])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getAllProcurementReturnCreatedEmployees().then(response => response.data).then(setCreatedByEmployees)
    }, []);
    let [addForm] = Form.useForm();
    // let [updateFrom] = Form.useForm();
    function buildFormItems(formInstance:FormInstance) {
        return <>
            <QuickCreatableSelectFormItem name={"supplierId"} label={"供货商"}
                                          onRefresh={queryAllProcurementSupplier}
                                          options={procurementReturnSuppliers.map(it => ({label: it.name, value: it.id,}))}
                                          onCreate={async (name)=>{
                                              let id = (await createProcurementSupplier({name})).data;
                                              procurementReturnSuppliers.push({id, name})
                                              setProcurementReturnSuppliers(Array.from(procurementReturnSuppliers))
                                              formInstance.setFieldValue("supplierId",id)
                                          }}/>
        </>
    }

    let navigate = useNavigate();
    return <>
        <DataPageLayout rightActions={<AuthorizationResource authorities={["采购_退货_创建"]}>
            <Button type={"primary"} onClick={() => {
                setOpenAddDrawer(true)
            }}><PlusOutlined/>下单</Button>
        </AuthorizationResource>}>
            <Table<QueryProcurementReturnResponse> className={globalStyle.rowClickableTable} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/procurementReturns/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setMarketIds(filters["supplier.name"] as number[])
                setCreatedByIds(filters["createdBy.name"] as number[])
                let filter = filters["status"] as unknown as ProcurementReturnStatus[];
                setStatus(filter ? filter[0] : undefined)
            }}>
                <Table.Column<QueryProcurementReturnResponse> filteredValue={supplierIds} dataIndex={["supplier", "name"]}
                                                        title={"供货商"}
                                                        filters={procurementReturnSuppliers.map(supplier => {
                                                            return {
                                                                text: supplier.name,
                                                                value: supplier.id,
                                                            }
                                                        })} render={(_, record) => {
                    return record.supplier.name
                }}/>
                <Table.Column dataIndex={"createdDateTime"} title={"创建时间"}
                              {...useTableFilterDateRangeColumnProps<QueryProcurementReturnResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? value[0].format() : undefined)
                                      setEndDate(value ? value[1].format() : undefined)
                                  }
                              })}
                              render={(value) => value.format(DATE_WITH_TIME_FORMATER)}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                {/*<Table.Column<QueryProcurementReturnResponse> dataIndex={"status"}*/}
                {/*                                        filteredValue={status ? [status] : []}*/}
                {/*                                        title={"状态"}*/}
                {/*                                        key={"status"}*/}
                {/*                                        filterMultiple={false}*/}
                {/*                                        filters={procurementReturnStatuses.map(it => ({*/}
                {/*                                            text: procurementReturnStatusMap[it],*/}
                {/*                                            value: it*/}
                {/*                                        }))} render={(value, record) => {*/}
                {/*    return value === "RECEIPT" ? <Link onClick={event => {*/}
                {/*        event.stopPropagation()*/}
                {/*    }}*/}
                {/*                                       to={`/procurementReturns/receipts/${record.receiptId}`}>已入库</Link> : procurementReturnStatusMap[value]*/}
                {/*}}/>*/}
                <Table.Column dataIndex={["createdBy", "name"]} title={"下单人员"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
            </Table>
        </DataPageLayout>
        <FormDrawer<ProcurementReturnFormData> form={addForm} onClose={() => setOpenAddDrawer(false)}
                                         title={"下单"}
                                         onConfirm={async (values) => {
                                             return createProcurementReturn(values.supplierId).then(response => {
                                                 setOpenAddDrawer(false)
                                                 query()
                                                 navigate(`/procurementReturns/${response.data}`)
                                             })
                                         }}
                                         open={openAddDrawer}>
            {buildFormItems(addForm)}
        </FormDrawer>
    </>
}
export default observerDashboardPageWrapper(ProcurementReturnPage, "procurementReturns", "采购退货")
